package xin.marcher.module.replenished.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import xin.marcher.framework.common.util.data.DataCuttingUtil;
import xin.marcher.module.common.constants.CoreConstant;
import xin.marcher.module.common.constants.diplomacy.AbstractRedisKeyConstants;
import xin.marcher.module.common.constants.replenished.CompensationConstants;
import xin.marcher.module.common.constants.replenished.RecoverableConstants;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.common.core.PageResult;
import xin.marcher.module.common.enums.inventory.InventoryStatusEnum;
import xin.marcher.module.common.enums.lifecycle.ProductStatusEnum;
import xin.marcher.module.common.enums.seller.SellerGroupStatusEnum;
import xin.marcher.module.common.enums.seller.SellerTypeEnum;
import xin.marcher.module.common.enums.seller.TrialSaleTypeEnum;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.replenished.converter.CompensationConverter;
import xin.marcher.module.replenished.domain.bo.AttributeExtendBO;
import xin.marcher.module.replenished.domain.bo.ProductSellerRelationBO;
import xin.marcher.module.replenished.domain.entity.AttributeExtendDO;
import xin.marcher.module.replenished.domain.entity.ProductDetailDO;
import xin.marcher.module.replenished.domain.entity.SkuSellerRelationDO;
import xin.marcher.module.replenished.domain.entity.StackSkuRelationDO;
import xin.marcher.module.replenished.domain.request.CompensationRequest;
import xin.marcher.module.replenished.redis.RedisReadWriteManager;
import xin.marcher.module.replenished.redis.RedisSortedSetCache;
import xin.marcher.module.replenished.remote.SellerRemote;
import xin.marcher.module.replenished.repository.ProductRelationRepository;
import xin.marcher.module.replenished.repository.ProductRepository;
import xin.marcher.module.replenished.repository.RedisManagerRepository;
import xin.marcher.module.replenished.service.CompensationService;
import xin.marcher.module.seller.domain.dto.SellerInfoDTO;
import xin.marcher.module.seller.domain.response.SellerGroupResponse;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 商品可补 业务实现类
 *
 * 
 */
@Service
public class CompensationServiceImpl implements CompensationService {

    @Resource
    private ProductRepository productRepository;
    @Autowired
    private ProductRelationRepository productRelationRepository;
    @Autowired
    private SellerRemote sellerRemote;
    @Autowired
    private RedisReadWriteManager redisReadWriteManager;
    @Autowired
    private RedisManagerRepository redisManagerRepository;
    @Resource
    private CompensationConverter compensationConverter;


    /**
     * 同步可补的数据入缓存
     *
     * @return
     */
    @Override
    public JsonResult syncCompensationProduct(CompensationRequest request) {
        // 分页查询商品信息，处理商品可补的数据
        Integer pageNo = 1;
        List<SellerGroupResponse> sellerInfoResponseList = querySellerGroupList(pageNo, request.getSellerGroupType());
        while (!CollectionUtils.isEmpty(sellerInfoResponseList)) {
            //1. 过滤卖家组的非有效状态信息数据
            List<SellerGroupResponse> sellerGroupResponseList = sellerGroupFilter(sellerInfoResponseList);
            //2. 根据卖家组获取卖家支持的可售商品列表
            List<SkuSellerRelationDO> sellerRelationDOList = queryAvailableProduct(sellerGroupResponseList);
            //3. 查询商品信息，并过滤非自营的商品,填充关于商品的扩展信息
            List<ProductDetailDO> skuInfoDOList = querySkuInfoList(sellerRelationDOList);
            //4. 解析屏蔽微仓的扩展json，对屏蔽的卖家ID进行过滤，并将详情的商品sku信息绑定到卖家上
            List<ProductSellerRelationBO> sellerFilterList = sellerFilter(skuInfoDOList, sellerRelationDOList, sellerInfoResponseList);
            //5.普通商品过滤(试销品过滤，存储条件过滤)
            List<ProductSellerRelationBO> itemFilterList = itemFilter(sellerFilterList);
            //6.组套商品过滤(试销品过滤，存储条件过滤)
            List<ProductSellerRelationBO> suitFilterList = suitFilter(itemFilterList);
            //7. 库存预警的状态填充状态
            buildInventoryStatus(suitFilterList);
            //8.读取历史的缓存信息，对已经存在的缓存进行diff处理，处理新增或者修改的数据更新缓存
            diffRecoverableCache(suitFilterList, sellerInfoResponseList);
            pageNo++;
            sellerInfoResponseList = querySellerGroupList(pageNo, request.getSellerGroupType());
        }
        return JsonResult.buildSuccess();
    }

    /**
     * 对卖家下的商品进行库存预警处理，填充商品库存预警状态
     *
     * @param suitFilterList
     */
    private void buildInventoryStatus(List<ProductSellerRelationBO> suitFilterList) {
        // 可补的场景是卖家ID
        List<Long> sellerIdList = suitFilterList.stream().map(ProductSellerRelationBO::getSellerId).collect(Collectors.toList());
        // 批量查询缓存
        Map<Long, List<String>> redisSetMap = redisReadWriteManager.getRedisSortedSet(sellerIdList, AbstractRedisKeyConstants::getWarningInventoryZsetKey);
        // 对卖家下的商品和缓存的预警商品进行预警状态填充
        for (ProductSellerRelationBO productSellerRelationBO : suitFilterList) {
            // 卖家的可补商品列表
            List<ProductDetailDO> productDetailList = productSellerRelationBO.getProductDetailList();
            List<String> skuIdList = redisSetMap.get(productSellerRelationBO.getSellerId());
            if (CollectionUtils.isEmpty(skuIdList)) {
                continue;
            }
            // 集合转换MAP
            Map<String, String> skuMap = skuIdList.stream().collect(Collectors.toMap(
                    s -> s, s -> s
            ));
            // 填充商品的预警状态
            for (ProductDetailDO productDetailDO : productDetailList) {
                if (skuMap.containsKey(productDetailDO.getSkuId())) {
                    productDetailDO.setInventoryStatus(InventoryStatusEnum.WARNING_STATUS.getCode());
                }
            }
        }
    }

    /**
     * 对卖家组状态非有效的进行过滤
     *
     * @param sellerInfoResponseList
     * @return
     */
    private List<SellerGroupResponse> sellerGroupFilter(List<SellerGroupResponse> sellerInfoResponseList) {
        // 过滤无效的卖家组信息
        return sellerInfoResponseList.stream()
                .filter(sellerGroupResponse -> SellerGroupStatusEnum.EFFECTIVE_STATUS.getCode().equals(sellerGroupResponse.getSellerGroupStatus()))
                .collect(Collectors.toList());
    }


    /**
     * 分页查询 卖家组信息
     *
     * @param pageNo
     */
    public List<SellerGroupResponse> querySellerGroupList(Integer pageNo, Integer sellerGroupType) {
        PageResult<SellerGroupResponse> sellerGroupPage =
                sellerRemote.getSellerGroupList(pageNo, CompensationConstants.SELLER_PAGE_SIZE, sellerGroupType);
        return sellerGroupPage.getContent();
    }

    /**
     * 返回卖家组支持的可售商品列表
     *
     * @param sellerInfoResponseList
     */
    private List<SkuSellerRelationDO> queryAvailableProduct(List<SellerGroupResponse> sellerInfoResponseList) {
        if (!CollectionUtils.isEmpty(sellerInfoResponseList)) {
            // 转换为所有的卖家组ID
            List<Long> sellerGroupIdSplitList =
                    sellerInfoResponseList.stream().map(response -> response.getSellerGroupId().longValue()).collect(Collectors.toList());

            return productRelationRepository.pageQueryAvailableProduct(sellerGroupIdSplitList);
        }
        return new ArrayList<>();
    }

    /**
     * 批量查询出对应的可售自营商品详情信息
     *
     * @param sellerRelationDOList
     * @return
     */
    private List<ProductDetailDO> querySkuInfoList(List<SkuSellerRelationDO> sellerRelationDOList) {
        // 获取到sku商品对应的扩展信息
        List<AttributeExtendDO> skuAttributeDOList = querySkuAttributeList(sellerRelationDOList);

        Map<String, AttributeExtendDO> skuAttributeMap = skuAttributeDOList.stream()
                .collect(Collectors.toMap(AttributeExtendDO::getParticipateId, Function.identity()));

        // 获取得到商品详细信息，注意此处需要涉及到卖家和商品的绑定关系处理(查询sku信息的时候是不涉及到卖家绑定关系的)
        // 默认集合初始大小为50000，避免扩容次数频繁，一般商品的数量最多也就是几万-几十万
        List<ProductDetailDO> productDetailAllList = new ArrayList<>(RecoverableConstants.SKU_INIT_NUM);
        if (!CollectionUtils.isEmpty(sellerRelationDOList)) {
            // 先获取到对应的skuID列表
            Set<String> skuIdList = sellerRelationDOList.stream().map(SkuSellerRelationDO::getSkuId).collect(Collectors.toSet());
            // 一次最大查询1000 skuId，多个分页查询,这里做数据切割
            List<Set<String>> splitList = DataCuttingUtil.dataCuttingString(skuIdList, RecoverableConstants.SKU_LIMIT_NUM);
            for (Set<String> skuIds : splitList) {
                List<ProductDetailDO> productDetailDOList = productRepository.queryProductInfoList(skuIds);
                if (!CollectionUtils.isEmpty(productDetailDOList)) {
                    for (ProductDetailDO productDetailDO : productDetailDOList) {
                        if (productDetailDO.getSellerType().equals(SellerTypeEnum.SELF.getCode())) {
                            AttributeExtendDO attributeExtendDO = skuAttributeMap.get(productDetailDO.getSkuId());
                            if (!Objects.isNull(attributeExtendDO)) {
                                productDetailDO.setAttributeContent(attributeExtendDO.getAttributeContent());
                            }
                            productDetailAllList.add(productDetailDO);
                        }
                    }
                }
            }
            // 查询返回商品的详情信息
            return productDetailAllList;
        }
        return new ArrayList<>();
    }

    /**
     * 对微仓被屏蔽的卖家进行过滤,并绑定到卖家上
     *
     * @param productDetailAllList   全部的商品明细
     * @param sellerRelationDOList   卖家可售商品集合
     * @param sellerInfoResponseList 卖家组信息集合
     * @return
     */
    private List<ProductSellerRelationBO> sellerFilter(List<ProductDetailDO> productDetailAllList, List<SkuSellerRelationDO> sellerRelationDOList, List<SellerGroupResponse> sellerInfoResponseList) {
        // 先转换集合为map，key为商品的skuId标识
        Map<String, ProductDetailDO> skuInfoDOMap = productDetailAllList.stream().collect(Collectors.toMap(ProductDetailDO::getSkuId, Function.identity()));
        // 按卖家ID进行分组，把一个卖家组下的商品分配到多个卖家上
        Map<SellerInfoDTO, List<SkuSellerRelationDO>> skuSellerRelationMap = buildSellerRelation(sellerRelationDOList, sellerInfoResponseList);

        // 返回的绑定卖家和商品sku的集合对象
        List<ProductSellerRelationBO> sellerRelationBOList = new ArrayList<>(sellerRelationDOList.size());
        // 遍历 卖家和商品关系集合，开始填充商品sku信息绑定到卖家组上
        for (Map.Entry<SellerInfoDTO, List<SkuSellerRelationDO>> entry : skuSellerRelationMap.entrySet()) {
            List<SkuSellerRelationDO> skuSellerRelationDOS = entry.getValue();
            SellerInfoDTO sellerInfoDTO = entry.getKey();
            Long sellerId = sellerInfoDTO.getSellerId().longValue();
            // 循环绑定卖家组下的商品关系
            ProductSellerRelationBO skuSellerRelationBO = new ProductSellerRelationBO();
            skuSellerRelationBO.setSellerInfoDTO(sellerInfoDTO);
            skuSellerRelationBO.setSellerId(sellerId);
            List<ProductDetailDO> productDetailList = new ArrayList<>();
            // 遍历卖家组下的可售商品列表
            for (SkuSellerRelationDO sellerRelationDO : skuSellerRelationDOS) {
                // 查询的数据集合中 存在这个商品数据
                if (skuInfoDOMap.containsKey(sellerRelationDO.getSkuId())) {
                    ProductDetailDO productDetailDO = skuInfoDOMap.get(sellerRelationDO.getSkuId());
                    // 验证商品是否和卖家互斥，屏蔽卖家的需要过滤
                    if (checkShieldingSellerId(productDetailDO, sellerId)) {
                        // 设置一下商品归属卖家组ID
                        productDetailDO.setSellerGroupId(sellerRelationDO.getSellerGroupId());
                        // 绑定数据到卖家组上
                        productDetailList.add(productDetailDO);
                    }
                }
            }
            skuSellerRelationBO.setProductDetailList(productDetailList);
            sellerRelationBOList.add(skuSellerRelationBO);
        }
        return sellerRelationBOList;
    }

    /**
     * 批量查询出对应的可售商品属性扩展信息
     *
     * @param skuSellerRelationDTOS
     * @return
     */
    private List<AttributeExtendDO> querySkuAttributeList(List<SkuSellerRelationDO> skuSellerRelationDTOS) {
        // 获取商品属性扩展信息
        if (!CollectionUtils.isEmpty(skuSellerRelationDTOS)) {
            // 先获取到对应的skuID列表
            Set<String> skuIdList =
                    skuSellerRelationDTOS.stream().map(SkuSellerRelationDO::getSkuId).collect(Collectors.toSet());
            return productRepository.pageQueryProductAttributeList(skuIdList);
        }
        return new ArrayList<>();
    }

    /**
     * 构建卖家组下的卖家和商品关系
     *
     * @param sellerRelationDOList
     * @return
     */
    private Map<SellerInfoDTO, List<SkuSellerRelationDO>> buildSellerRelation(List<SkuSellerRelationDO> sellerRelationDOList, List<SellerGroupResponse> sellerInfoResponseList) {
        //卖家ID和商品关系集合
        Map<SellerInfoDTO, List<SkuSellerRelationDO>> sellerInfoAllMap = new HashMap<>(sellerRelationDOList.size());
        // 转换集合
        Map<Long, SellerGroupResponse> sellerGroupResponseMap = sellerInfoResponseList.stream()
                .collect(Collectors.toMap(response -> response.getSellerGroupId().longValue(), Function.identity()));
        // 按卖家组ID 进行分组，商品归属到一个卖家ID下
        Map<Long, List<SkuSellerRelationDO>> skuSellerRelationMap = sellerRelationDOList.stream().collect(Collectors.groupingBy(SkuSellerRelationDO::getSellerGroupId));
        // 开始循环卖家组可售商品和卖家组的关系，转换为卖家可售商品和卖家关系
        for (Map.Entry<Long, List<SkuSellerRelationDO>> entry : skuSellerRelationMap.entrySet()) {
            List<SkuSellerRelationDO> skuSellerRelationDOS = entry.getValue();
            Long sellerGroupId = entry.getKey();
            // 命中到对应的卖家组信息
            if (sellerGroupResponseMap.containsKey(sellerGroupId)) {
                SellerGroupResponse sellerGroupResponse = sellerGroupResponseMap.get(sellerGroupId);
                // 获取卖家组下的卖家列表信息
                List<SellerInfoDTO> sellerInfoDTOList = sellerGroupResponse.getSellerInfoDTOList();
                // 将卖家ID和卖家可售商品关系绑定上
                if (!CollectionUtils.isEmpty(sellerInfoDTOList)) {
                    for (SellerInfoDTO sellerInfoDTO : sellerInfoDTOList) {
                        sellerInfoAllMap.put(sellerInfoDTO, skuSellerRelationDOS);
                    }
                }
            }
        }
        return sellerInfoAllMap;
    }

    /**
     * 进行item级别的商品过滤(试销商品需要验证是否有试销仓,商品的存储条件匹配)
     *
     * @param skuInfoDOList
     */
    private List<ProductSellerRelationBO> itemFilter(List<ProductSellerRelationBO> skuInfoDOList) {
        if (!CollectionUtils.isEmpty(skuInfoDOList)) {
            //1. 验证商品是否属于试销品(item_status,商品状态,2-试销上架),试销商品需要验证是否有试销仓的标识，没有需要过滤
            List<ProductSellerRelationBO> trialSalesList = filterTrialSales(skuInfoDOList);
            //2.商品的存储条件进行过滤，商品的存储条件必须和归属仓的存储条件一致
            return filterStorage(trialSalesList);
        }
        return new ArrayList<>();
    }

    /**
     * 进行套装商品的商品过滤(试销商品需要验证是否有试销仓,商品的存储条件匹配)
     *
     * @param skuInfoDOList
     * @return
     */
    private List<ProductSellerRelationBO> suitFilter(List<ProductSellerRelationBO> skuInfoDOList) {
        if (!CollectionUtils.isEmpty(skuInfoDOList)) {
            //1.反向寻找到套装商品归属的item信息(此处绑定上还需要指向的上级组套商品sku，否则处理关系有问题)
            List<ProductSellerRelationBO> suitItemDOList = querySuitList(skuInfoDOList);
            // 执行属于组套商品的下级商品信息，如果不符合条件则过滤
            //2. 验证商品是否属于试销品(item_status,商品状态,2-试销上架),试销商品需要验证是否有试销仓的标识，没有需要过滤
            List<ProductSellerRelationBO> trialSalesList = filterStackTrialSales(suitItemDOList);
            //3.商品的存储条件进行过滤，商品的存储条件必须和归属仓的存储条件一致
            return filterStackStorage(trialSalesList);
        }
        return new ArrayList<>();
    }

    /**
     * 转换模型，将 验证成功的组套商品信息 转换为方便处理的模型对象
     *
     * @param productSellerRelationBOList
     * @return
     */
    private Map<Long, Map<String, ProductDetailDO>> buildMigrateProductMap(List<ProductSellerRelationBO> productSellerRelationBOList) {
        Map<Long, Map<String, ProductDetailDO>> productMigrateMap = new HashMap<>(productSellerRelationBOList.size());
        for (ProductSellerRelationBO productSellerRelationBO : productSellerRelationBOList) {
            // 卖家的可售商品信息
            List<ProductDetailDO> productDetailList = productSellerRelationBO.getProductDetailList();
            // 转换为商品sku对应商品详情的关系
            Map<String, ProductDetailDO> productDetailDOMap = productDetailList.stream().collect(Collectors.toMap(ProductDetailDO::getSkuId, Function.identity()));
            // 转换卖家ID对应卖家可售商品信息
            productMigrateMap.put(productSellerRelationBO.getSellerInfoDTO().getSellerId().longValue(), productDetailDOMap);
        }
        return productMigrateMap;
    }

    /**
     * 查询套装商品的item信息，并对返回的套装商品对应的item绑定到卖家上
     *
     * @param skuInfoDOList
     * @return
     */
    private List<ProductSellerRelationBO> querySuitList(List<ProductSellerRelationBO> skuInfoDOList) {
        // 查询那些是组套商品
        List<StackSkuRelationDO> stackSkuRelationAllList = queryStackSkuListByIds(skuInfoDOList);
        // 没有组套商品的直接返回空集合
        if (CollectionUtils.isEmpty(stackSkuRelationAllList)) {
            return skuInfoDOList;
        }
        //获取组套商品的详情集合信息(包含item信息)
        List<ProductDetailDO> productDetailDOList = queryProductInfoList(stackSkuRelationAllList);
        // 将组套商品绑定到对应的卖家身上(维度都是卖家维度)
        return buildSuitBinding(productDetailDOList, skuInfoDOList, stackSkuRelationAllList);
    }

    /**
     * 将套装商品的详细信息绑定到卖家上
     *
     * @param productDetailDOList     sku对应组套商品详情信息
     * @param skuInfoDOList           全部商品信息
     * @param stackSkuRelationAllList 组套sku信息
     * @return
     */
    private List<ProductSellerRelationBO> buildSuitBinding(List<ProductDetailDO> productDetailDOList, List<ProductSellerRelationBO> skuInfoDOList, List<StackSkuRelationDO> stackSkuRelationAllList) {
        List<ProductSellerRelationBO> productSellerRelationBOList = compensationConverter.converterSellerList(skuInfoDOList);
        // sku对应的组套商品详情(对应组套商品的stackSkuId)
        Map<String, ProductDetailDO> productDetailMap = productDetailDOList.stream().collect(Collectors.toMap(ProductDetailDO::getSkuId, Function.identity()));
        //组套的商品集合(一个商品下多个物料sku组装而成)
        Map<String, List<StackSkuRelationDO>> stackSkuRelationMap = stackSkuRelationAllList.stream().collect(Collectors.groupingBy(StackSkuRelationDO::getSkuId));
        // 开始遍历全部的商品信息
        for (ProductSellerRelationBO productSellerRelationBO : productSellerRelationBOList) {
            // 单个卖家下的商品列表
            List<ProductDetailDO> productDetailList = productSellerRelationBO.getProductDetailList();
            // 验证这个商品是否组套商品
            for (ProductDetailDO productDetailDO : productDetailList) {
                // 命中到了对应的组套商品
                if (stackSkuRelationMap.containsKey(productDetailDO.getSkuId())) {
                    // 标记为组套商品
                    productDetailDO.setProductType(2);
                    // 同时存储对应的组套商品详情信息
                    List<StackSkuRelationDO> stackSkuRelationList = stackSkuRelationMap.get(productDetailDO.getSkuId());
                    List<ProductDetailDO> productDetailDOS = new ArrayList<>();
                    for (StackSkuRelationDO stackSkuRelationDO : stackSkuRelationList) {
                        if (productDetailMap.containsKey(stackSkuRelationDO.getStackSkuId())) {
                            ProductDetailDO productDetail = productDetailMap.get(stackSkuRelationDO.getStackSkuId());
                            productDetailDOS.add(productDetail);
                        }
                    }
                    productDetailDO.setProductDetailList(productDetailDOS);
                }
            }
        }
        return productSellerRelationBOList;
    }

    /**
     * 根据skuId 批量查询是否组套商品
     *
     * @param skuInfoDOList
     * @return
     */
    private List<StackSkuRelationDO> queryStackSkuListByIds(List<ProductSellerRelationBO> skuInfoDOList) {
        // 先获取所有的商品信息，并去重
        Set<String> skuIdList = buildSkuIdList(skuInfoDOList);
        // 分页查询是否组套商品
        return productRelationRepository.pageQueryStackSkuListByIds(skuIdList);

    }


    /**
     * 获取组套商品的详情集合信息
     *
     * @param stackSkuRelationAllList
     * @return
     */
    private List<ProductDetailDO> queryProductInfoList(List<StackSkuRelationDO> stackSkuRelationAllList) {
        // 获取组套商品的sku列表，通过sku列表联合查询得到对应的item信息
        Set<String> stackSkuIdList = stackSkuRelationAllList.stream().map(StackSkuRelationDO::getStackSkuId).collect(Collectors.toSet());
        //查询组套商品详情集合信息
        return productRepository.pageQueryProductInfoList(stackSkuIdList);
    }

    /**
     * 构建出准备查询得sku数据集合
     *
     * @param skuInfoDOList
     * @return
     */
    private Set<String> buildSkuIdList(List<ProductSellerRelationBO> skuInfoDOList) {
        Set<String> skuIdAllList = new HashSet<>(RecoverableConstants.SKU_INIT_NUM);
        for (ProductSellerRelationBO productSellerRelationBO : skuInfoDOList) {
            List<ProductDetailDO> productDetailList = productSellerRelationBO.getProductDetailList();
            Set<String> skuIdList = productDetailList.stream().map(ProductDetailDO::getSkuId).collect(Collectors.toSet());
            skuIdAllList.addAll(skuIdList);
        }
        return skuIdAllList;
    }

    /**
     * 对试销的商品进行试销仓验证
     *
     * @param skuInfoDOList
     * @return
     */
    private List<ProductSellerRelationBO> filterTrialSales(List<ProductSellerRelationBO> skuInfoDOList) {
        List<ProductSellerRelationBO> productSellerRelationAllList = compensationConverter.converterSellerList(skuInfoDOList);
        if (!CollectionUtils.isEmpty(productSellerRelationAllList)) {
            //遍历每个卖家下的商品列表
            for (ProductSellerRelationBO productSellerRelation : productSellerRelationAllList) {
                List<ProductDetailDO> productDetailList = productSellerRelation.getProductDetailList();
                SellerInfoDTO sellerInfoDTO = productSellerRelation.getSellerInfoDTO();
                // 获取属于试销仓的商品信息,普通商品过滤
                List<ProductDetailDO> trialSalesList = productDetailList.stream()
                        .filter(productDetailDO -> productDetailDO.getItemStatus().equals(ProductStatusEnum.TRY_SALE_ON_MARKET.getCode()))
                        .collect(Collectors.toList());

                // 判断是否需要验证试销仓，如果没用试销商品则不需要校验
                if (CollectionUtils.isEmpty(trialSalesList)) {
                    continue;
                }
                // 校验商品试销标签，仓是否也是试销仓的标签，不是则过滤
                if (sellerInfoDTO.getTrialSaleLabel().equals(TrialSaleTypeEnum.TRIAL_SALE_TYPE_NO.getCode())) {
                    // 移除不符合条件商品
                    productDetailList.removeAll(trialSalesList);
                    productSellerRelation.setProductDetailList(productDetailList);
                }
            }
        }
        return productSellerRelationAllList;
    }

    /**
     * 对普通商品下的组套商品进行验证
     *
     * @param skuInfoDOList
     * @return
     */
    private List<ProductSellerRelationBO> filterStackTrialSales(List<ProductSellerRelationBO> skuInfoDOList) {
        List<ProductSellerRelationBO> productSellerRelationAllList = compensationConverter.converterSellerList(skuInfoDOList);
        if (!CollectionUtils.isEmpty(productSellerRelationAllList)) {
            //遍历每个卖家下的商品列表
            for (ProductSellerRelationBO productSellerRelation : productSellerRelationAllList) {
                List<ProductDetailDO> productDetailList = productSellerRelation.getProductDetailList();
                SellerInfoDTO sellerInfoDTO = productSellerRelation.getSellerInfoDTO();
                // 验证组套商品
                List<ProductDetailDO> productDetailDOList = productDetailList.stream().filter(productDetailDO -> {
                    //商品属于组套商品类型，验证组套商品层级的商品是否满足
                    if (productDetailDO.getProductType().equals(2)) {
                        // 任意一个组套商品不通过，都影响上级的商品被过滤，但是不能影响普通商品
                        if (checkTrialSales(productDetailDO.getProductDetailList(), sellerInfoDTO)) {
                            return false;
                        }
                    }
                    return true;
                }).collect(Collectors.toList());

                productSellerRelation.setProductDetailList(productDetailDOList);
            }
        }
        return productSellerRelationAllList;
    }

    /**
     * 组套商品验证试销仓
     *
     * @param productDetailDOList
     * @param sellerInfoDTO
     * @return
     */
    private Boolean checkTrialSales(List<ProductDetailDO> productDetailDOList, SellerInfoDTO sellerInfoDTO) {
        for (ProductDetailDO productDetailDO : productDetailDOList) {
            // 组套商品中，有任意一个 属于试销品，且卖家不是试销仓，都移除上级的父类商品
            if (productDetailDO.getItemStatus().equals(ProductStatusEnum.TRY_SALE_ON_MARKET.getCode()) && sellerInfoDTO.getTrialSaleLabel().equals(TrialSaleTypeEnum.TRIAL_SALE_TYPE_NO.getCode())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 商品存储条件和卖家仓匹配
     *
     * @param trialSalesList
     * @return
     */
    private List<ProductSellerRelationBO> filterStorage(List<ProductSellerRelationBO> trialSalesList) {
        List<ProductSellerRelationBO> productSellerRelationAllList = compensationConverter.converterSellerList(trialSalesList);
        if (!CollectionUtils.isEmpty(productSellerRelationAllList)) {
            // 遍历卖家，验证可售商品的存储条件是否和卖家仓的存储条件一致
            for (ProductSellerRelationBO productSellerRelationBO : productSellerRelationAllList) {
                List<ProductDetailDO> productDetailList = productSellerRelationBO.getProductDetailList();

                List<ProductDetailDO> productDetailDOList = productDetailList.stream().filter(productDetailDO -> {
                    Integer storeConditionType = productDetailDO.getStoreConditionType();
                    // 卖家仓的存储条件
                    List<Integer> storeLabelList = productSellerRelationBO.getSellerInfoDTO().getStoreLabelList();
                    // 满足卖家仓的存储条件才保留
                    if (storeLabelList.contains(storeConditionType)) {
                        return true;
                    }
                    return false;
                }).collect(Collectors.toList());

                productSellerRelationBO.setProductDetailList(productDetailDOList);
            }
        }
        return productSellerRelationAllList;
    }

    /**
     * 过滤组套商品的存储条件
     *
     * @param skuInfoDOList
     * @return
     */
    private List<ProductSellerRelationBO> filterStackStorage(List<ProductSellerRelationBO> skuInfoDOList) {
        List<ProductSellerRelationBO> productSellerRelationAllList = compensationConverter.converterSellerList(skuInfoDOList);
        if (!CollectionUtils.isEmpty(productSellerRelationAllList)) {
            //卖家遍历
            for (ProductSellerRelationBO productSellerRelationBO : productSellerRelationAllList) {
                List<ProductDetailDO> productDetailList = productSellerRelationBO.getProductDetailList();
                SellerInfoDTO sellerInfoDTO = productSellerRelationBO.getSellerInfoDTO();
                //卖家的商品列表
                List<ProductDetailDO> productDetailDOList = productDetailList.stream().filter(productDetailDO -> {
                    // 验证属于组套商品的信息
                    if (productDetailDO.getProductType().equals(2)) {
                        if (checkStackStorage(productDetailDO.getProductDetailList(), sellerInfoDTO)) {
                            return false;
                        }
                    }
                    return true;
                }).collect(Collectors.toList());

                productSellerRelationBO.setProductDetailList(productDetailDOList);
            }
        }
        return productSellerRelationAllList;
    }


    /**
     * 组套商品验证试销仓
     *
     * @param productDetailDOList
     * @param sellerInfoDTO
     * @return
     */
    private Boolean checkStackStorage(List<ProductDetailDO> productDetailDOList, SellerInfoDTO sellerInfoDTO) {
        for (ProductDetailDO productDetailDO : productDetailDOList) {
            // 组套商品中，有任意一个 属于试销品，且卖家不是试销仓，都移除上级的父类商品
            // 商品的存储条件
            Integer storeConditionType = productDetailDO.getStoreConditionType();
            // 卖家仓的存储条件
            List<Integer> storeLabelList = sellerInfoDTO.getStoreLabelList();
            // 不满足卖家仓的存储条件,进行移除
            if (!storeLabelList.contains(storeConditionType)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 对 已经缓存的历史数据进行diff处理，处理缓存 缓存变更
     *
     * @param sellerFilterList     变更数据对象
     * @param sellerRelationDOList 查询的初始对象
     * @return
     */
    private void diffRecoverableCache(List<ProductSellerRelationBO> sellerFilterList, List<SellerGroupResponse> sellerRelationDOList) {
        // 获取所有的卖家ID
        List<SellerInfoDTO> sellerInfoDTOList = buildSellerInfoDTOList(sellerRelationDOList);
        // 获取所有的卖家ID
        Set<Long> sellerIdList = sellerInfoDTOList.stream().map(dto -> dto.getSellerId().longValue()).collect(Collectors.toSet());
        //2.数据差集比较,并刷入缓存差异信息
        diffCache(sellerIdList, sellerFilterList);
    }

    /**
     * 获取卖家组下所有的卖家ID
     *
     * @param sellerRelationDOList
     * @return
     */
    private List<SellerInfoDTO> buildSellerInfoDTOList(List<SellerGroupResponse> sellerRelationDOList) {
        List<SellerInfoDTO> sellerInfoDTOList = new ArrayList<>(sellerRelationDOList.size() * 10);
        if (!CollectionUtils.isEmpty(sellerRelationDOList)) {
            for (SellerGroupResponse sellerGroupResponse : sellerRelationDOList) {
                sellerInfoDTOList.addAll(sellerGroupResponse.getSellerInfoDTOList());
            }
        }
        return sellerInfoDTOList;
    }

    /**
     * 开始进行数据差集的处理
     *
     * @param sellerIdList
     * @param productSellerRelationBOList
     */
    private void diffCache(Set<Long> sellerIdList, List<ProductSellerRelationBO> productSellerRelationBOList) {
        //1.批量查询缓存
        Map<Long, List<String>> redisSetMap = redisReadWriteManager.getRedisSortedSet(sellerIdList, AbstractRedisKeyConstants::getSellerTypeCompensateSkuZsetKey);
        // 转换缓存的值为具体的对象
        Map<Long, Map<String, ProductDetailDO>> productSellerCacheMap = redisManagerRepository.converterProductSellerCache(redisSetMap);
        // 进行数据差集处理
        Map<String, RedisSortedSetCache> diffSortedSetCache = redisManagerRepository.diffProduct(productSellerRelationBOList, productSellerCacheMap, AbstractRedisKeyConstants::getSellerTypeCompensateSkuZsetKey);
        // 执行数据缓存更新
        redisReadWriteManager.flushIncrSortedSetMap(diffSortedSetCache);
    }

    /**
     * 对商品是否屏蔽微仓进行校验
     *
     * @param productDetailDO
     * @param sellerId
     * @return
     */
    private Boolean checkShieldingSellerId(ProductDetailDO productDetailDO, Long sellerId) {
        String attributeContent = productDetailDO.getAttributeContent();
        // 转换为扩展信息对象
        AttributeExtendBO attributeExtendBO = JsonUtil.json2Object(attributeContent, AttributeExtendBO.class);

        if (Objects.isNull(attributeExtendBO) || StringUtils.isEmpty(attributeExtendBO.getShieldingSellerId())) {
            return true;
        }
        // 验证是否命中屏蔽微仓，命中说明需要过滤
        List<String> sellerIds = Arrays.asList(attributeExtendBO.getShieldingSellerId().split(CoreConstant.COMMA));
        return !sellerIds.contains(String.valueOf(sellerId));
    }


    /**
     * 对组套商品进行合并，将符合条件的组套商品以及非组套商品的结果集合并返回
     *
     * @param skuInfoDOList               全部的商品信息
     * @param suitItemDOList              组套商品信息
     * @param productSellerRelationBOList 验证成功的组套商品信息
     * @return
     */
    @Deprecated
    private List<ProductSellerRelationBO> migrateProduct(List<ProductSellerRelationBO> skuInfoDOList, List<ProductSellerRelationBO> suitItemDOList, List<ProductSellerRelationBO> productSellerRelationBOList) {
        //1. 返回不可售的商品列表
        List<ProductSellerRelationBO> productSellerRelationBOList1 = diffProductList(suitItemDOList, productSellerRelationBOList, true);
        //2.将差集数据，视为不符合条件的商品从全部商品中移除
        return diffProductList(skuInfoDOList, productSellerRelationBOList1, false);
    }

    /**
     * 进行 数据去除过滤处理
     *
     * @param productAllList 全量数据集合
     * @param diffFailList   差异数据对象
     * @param isAnode        true 返回 全量和差异集合的差异数据，false 全量过滤掉差异数据集合
     * @return
     */
    @Deprecated
    private List<ProductSellerRelationBO> diffProductList(List<ProductSellerRelationBO> productAllList, List<ProductSellerRelationBO> diffFailList, boolean isAnode) {
        List<ProductSellerRelationBO> productDiffAllList = compensationConverter.converterSellerList(productAllList);
        // 作为接下来校验差异的比较条件
        Map<Long, Map<String, ProductDetailDO>> productMigrateMap = buildMigrateProductMap(diffFailList);
        //1. 从商品中 验证成功的商品差集(未能校验成功的商品信息需要从卖家组下移除)
        for (ProductSellerRelationBO productSellerRelationBO : productDiffAllList) {
            // 卖家的商品列表
            List<ProductDetailDO> productDetailList = productSellerRelationBO.getProductDetailList();
            //isAnode  true 表示需要返回2个数据集的差异，false 表示要从全量数据集删除对应的数据信息(逻辑相反)，如未命中，说明当前卖家的商品都属于不可售
            if (productMigrateMap.containsKey(productSellerRelationBO.getSellerInfoDTO().getSellerId())) {
                // 可售商品集合对象
                Map<String, ProductDetailDO> productDetailDOMap = productMigrateMap.get(productSellerRelationBO.getSellerInfoDTO().getSellerId());
                // 返回差异数据
                if (isAnode) {
                    List<ProductDetailDO> diffProductList = productDetailList.stream()
                            .filter(productDetailDO -> !productDetailDOMap.containsKey(productDetailDO.getSkuId()))
                            .collect(Collectors.toList());
                    // 填充卖家的不可售商品列表
                    productSellerRelationBO.setProductDetailList(diffProductList);

                } else {
                    // 删除差异数据(命中的都是不可售商品)
                    List<ProductDetailDO> diffProductList = productDetailList.stream()
                            .filter(productDetailDO -> productDetailDOMap.containsKey(productDetailDO.getSkuId()))
                            .collect(Collectors.toList());
                    // 填充卖家的可售商品列表
                    productSellerRelationBO.setProductDetailList(diffProductList);
                }
            }
        }
        return productDiffAllList;
    }
}
